﻿using NUnit.Framework;
using System.Threading;
using TI_BLE_HCI_ClientLib.Controllers;
using TI_BLE_HCI_ClientLib.HCIBaseEntities;
using TI_BLE_HCI_ClientLib.HCICommands;
using TI_BLE_HCI_ClientLib.HCIEvents;

namespace TI_BLE_HCI_ClientLib.Tests
{
    [TestFixture]
    public class HCISerialControllerTester
    {
        [Test]
        public void GAP_DeviceInit_TestConversation()
        {
            HCISimpleSerialCentralProfileController controller = new HCISimpleSerialCentralProfileController("COM19", 115200);

            AutoResetEvent are = new AutoResetEvent(false);
            HCIEvent hciEvent = null;

            controller.HCIEventReceived += ((evt) => { are.Set(); hciEvent = evt; });

            controller.Start();

            // INVIO COMANDO GAP_DEVICE_INIT
            controller.SendCommand(
                new HCICommand_GAP_Device_Init(
                    HCICommand_GAP_Device_Init.ProfileRoleEnum.GAPProfileCentral,
                    5,
                    new byte[16],
                    new byte[16],
                    1)
                    );

            // VERIFICA RICEZIONE EVENTO COMMAND_STATUS CON ESITO POSITIVO

            var ok = are.WaitOne(1000);

            if (!ok) Assert.Fail("HCIEvent NOT RECEIVED WITHIN TIMEOUT");

            HCIEvent_GAP_Command_Status hciEventCommandStatus = hciEvent as HCIEvent_GAP_Command_Status;

            Assert.AreEqual(HCIVendorSpecificEventHostErrorCode.Success, hciEventCommandStatus.Status);
            Assert.AreEqual(HCIVendorSpecificCommandOpcode.GAP_Device_Init, hciEventCommandStatus.Opcode);
            Assert.AreEqual(0, hciEventCommandStatus.DataLen);
            Assert.AreEqual(0, hciEventCommandStatus.CommandPayload.Length);

            // VERIFICA RICEZIONE EVENTO DEVICE_INIT_DONE CON ESITO POSITIVO

            ok = are.WaitOne(1000);

            if (!ok) Assert.Fail("HCIEvent NOT RECEIVED WITHIN TIMEOUT");

            HCIEvent_GAP_Device_Init_Done hciEventDeviceInitDone = hciEvent as HCIEvent_GAP_Device_Init_Done;

            Assert.AreEqual(HCIVendorSpecificEventHostErrorCode.Success, hciEventDeviceInitDone.Status);
        }
    }
}